package net.skystudio.es.service.impl;

import net.skystudio.es.common.SortParams;
import net.skystudio.es.elastic.repository.HotWordRepository;
import net.skystudio.es.entity.HotWords;
import net.skystudio.es.service.HotWordService;
import net.skystudio.es.util.BeansUtil;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class HotWordServiceImpl implements HotWordService {

    @Autowired
    private HotWordRepository hotWordRepository;

    @Autowired
    private RestHighLevelClient client;

    private static final String INDEX_NAME = "index_hotwords";

    @Override
    public List<String> topTen(String key) {
        prepareProcess(key);
        SortParams sort = new SortParams();
        sort.setFieldName("hotWord");
        sort.setSortOrder(SortOrder.DESC);
        List<String> result = new ArrayList<>();
        SearchResponse searchResponse = getSearchResponse(sort);
        SearchHit[] hits = searchResponse.getHits().getHits();
        if(hits.length == 0) {
            return null;
        }
        Arrays.stream(hits).forEach(s -> {
            Map<String, Object> sourceAsMap = s.getSourceAsMap();
            result.add(sourceAsMap.get("hotWord").toString());
        });
        return result;
    }

    private boolean exists(String hotWord) {
        SearchResponse searchResponse = getSearchResponse(hotWord);
        SearchHit[] hits = searchResponse.getHits().getHits();
        if (hits.length > 0) {
            return true;
        }
        return false;
    }

    private void save(String hotWord) {
        HotWords hotWords = new HotWords();
        hotWords.setId(UUID.randomUUID().toString());
        hotWords.setHotWord(hotWord);
        hotWords.setCount(1L);
        hotWordRepository.save(hotWords);
    }

    private void update(String hotWord) {
        SearchResponse searchResponse = getSearchResponse(hotWord);
        SearchHit[] hits = searchResponse.getHits().getHits();
        Map<String, Object> sourceAsMap = hits[0].getSourceAsMap();
        HotWords hotWords = null;
        try {
            hotWords = (HotWords) BeansUtil.m2o(sourceAsMap, HotWords.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        hotWords.setCount(hotWords.getCount() + 1);
        hotWordRepository.save(hotWords);
    }

    private void prepareProcess(String key) {
        if(StringUtils.isNotEmpty(key)){
            if (exists(key)) {
                update(key);
            } else {
                save(key);
            }
        }
    }

    private SearchResponse getSearchResponse(SortParams sort) {
        return getSearchResponse(null, sort);
    }

    private SearchResponse getSearchResponse(String hotWord) {
        return getSearchResponse(hotWord, null);
    }

    private SearchResponse getSearchResponse(String hotWord, SortParams sort) {
        //查询
        MatchQueryBuilder queryBuilder = new MatchQueryBuilder("hotWord", hotWord);
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(queryBuilder);
        if (sort != null) {
            sourceBuilder.sort(sort.getFieldName(), sort.getSortOrder());
        }
        searchRequest.source(sourceBuilder);
        try {
            return client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }


}
